package cn.abcode.test.springbootsecurity.demo.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class LoginFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String method = request.getMethod().toUpperCase();
        if(!"POST".equals(method)){
            throw new AuthenticationServiceException("认证方法不支持：" + method + "方法的请求");
        }
        String sessionCode = (String) request.getSession().getAttribute("verify_code");
        //请求参数数据格式
        String contentType = request.getContentType();
        System.out.println(contentType);
        if(MediaType.APPLICATION_JSON_VALUE.equals(contentType)
                || MediaType.APPLICATION_PROBLEM_JSON_UTF8_VALUE.equals(contentType)
                || "text/plain;charset=UTF-8".equals(contentType)
        ){

            Map<String ,Object> paramMap = new HashMap<>();
            try {
                Map<String, String[]> map =  request.getParameterMap();
                paramMap = new ObjectMapper().readValue(request.getInputStream(),Map.class);
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                String paramCode = paramMap.get("verifyCode").toString();
                checkVerifyCode(request, paramCode, sessionCode);
            }

            String username = paramMap.get("account").toString();
            String password = paramMap.get("pwd").toString();

            if(username == null){
                username = "";
            }
            if(password == null){
                password = "";
            }
            username = username.trim();

            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);

        }else{
            String paramCode = request.getParameter("verifyCode");

            checkVerifyCode(request, paramCode, sessionCode);

            return super.attemptAuthentication(request, response);
        }


    }

    public void checkVerifyCode(HttpServletRequest request, String paramCode, String sessionCode){
        if(StringUtils.isEmpty(paramCode) || StringUtils.isEmpty(sessionCode) || !paramCode.equals(sessionCode)){
            throw new AuthenticationServiceException("验证码不正确");
        }
    }

}
